package com.ruoyi.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ruoyi.domain.Book;
import com.ruoyi.domain.LendMessage;
import com.ruoyi.domain.Penalty;
import com.ruoyi.domain.dto.EmailDto;
import com.ruoyi.mapper.BookMapper;
import com.ruoyi.mapper.LendMessageMapper;
import com.ruoyi.mapper.PenaltyMapper;
import com.ruoyi.pojo.dto.QuestionDto;
import com.ruoyi.service.ILendMessageService;
import com.ruoyi.service.IQuestionService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import com.ruoyi.mapper.MessageMapper;
import com.ruoyi.domain.Message;
import com.ruoyi.service.IMessageService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 消息中心Service业务层处理
 *
 * @author qyb
 * @date 2023-12-26
 */
@Service
public class MessageServiceImpl implements IMessageService
{
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private LendMessageMapper lendMessageMapper;
    @Autowired
    private SysDictDataMapper   sysDictDataMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private PenaltyMapper penaltyMapper;
    @Autowired
    private ILendMessageService lendMessageService;

    @Autowired
    public IQuestionService questionService;
    /**
     * 查询消息中心
     *
     * @param messageId 消息中心主键
     * @return 消息中心
     */
    @Override
    public Message selectMessageByMessageId(Long messageId)
    {
        return messageMapper.selectMessageByMessageId(messageId);
    }

    /**
     * 查询消息中心列表
     *
     * @param message 消息中心
     * @return 消息中心
     */
    @Override
    public List<Message> selectMessageList(Message message)
    {
        return messageMapper.selectMessageList(message);
    }



    /**
     * 修改消息中心
     *
     * @param message 消息中心
     * @return 结果
     */
    @Override
    public int updateMessage(Message message)
    {
        message.setUpdateTime(DateUtils.getNowDate());
        return messageMapper.updateMessage(message);
    }

    /**
     * 批量删除消息中心
     *
     * @param messageIds 需要删除的消息中心主键
     * @return 结果
     */
    @Override
    public int deleteMessageByMessageIds(Long[] messageIds)
    {
        return messageMapper.deleteMessageByMessageIds(messageIds);
    }

    /**
     * 删除消息中心信息
     *
     * @param messageId 消息中心主键
     * @return 结果
     */
    @Override
    public int deleteMessageByMessageId(Long messageId)
    {
        return messageMapper.deleteMessageByMessageId(messageId);
    }




    /**
     * 发送到期消息
     *
     * @return 结果
     */

    @Override
    public void sendCallMessage()
    {

        int lendExpiring = Integer.parseInt(sysDictDataMapper.selectValueByType("sys_lend_expiring"));

        List<EmailDto> DueBookList = lendMessageMapper.selectDueBookByDay(lendExpiring);
//            设置时间格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        发送催还图书消息
        for (EmailDto item: DueBookList
             ) {
            String shouldBackTime = sf.format(item.getShouldBackTime());
////          发送邮件
//            SimpleMailMessage mailMessage = new SimpleMailMessage();
            String text = "您借阅的《" + item.getName() + "》  借阅id = " + item.getLendId() + " 将于" + shouldBackTime +"到期，请及时归还！";
////            设置发送人
//            mailMessage.setFrom("3407976203@qq.com");
////            邮件主题
//            mailMessage.setSubject("图书管理系统：还书通知");
////            邮件内容
//            mailMessage.setText(text);
////            收件人
//            mailMessage.setTo(item.getEmail());
//            javaMailSender.send(mailMessage);

            //添加到个人消息中
            QuestionDto questionDto = new QuestionDto();
            questionDto.setContent(text);
            questionDto.setUserId(item.getUserId());
//            questionDto.setName(item.getName());
            questionDto.setDescription(item.getName());
            questionDto.setIsUserTrue(1);
            questionService.addQuestion(questionDto);


//        保存发送信息
//            Message message = new Message();
//            message.setContent(text);
//            message.setUserId(item.getUserId());
//            message.setCreateTime(DateUtils.getNowDate());
//            messageMapper.insertMessage(message);

        }

//        发送催缴罚款信息
        List<EmailDto> overDueList = penaltyMapper.selectOverDueList();
        for (EmailDto item: overDueList
        ) {
//            String shouldBackTime = sf.format(item.getShouldBackTime());
////          发送邮件
//            SimpleMailMessage mailMessage = new SimpleMailMessage();
            String text = "您有一笔罚款记录{罚款id=" + item.getLendId() +"}已逾期，请及时缴清！";
////            设置发送人
//            mailMessage.setFrom("3407976203@qq.com");
////            邮件主题
//            mailMessage.setSubject("图书管理系统：还款提醒");
////            邮件内容
//            mailMessage.setText(text);
////            收件人
//            mailMessage.setTo(item.getEmail());
//            javaMailSender.send(mailMessage);

            //添加到个人消息中
            QuestionDto questionDto = new QuestionDto();
            questionDto.setContent(text);
            questionDto.setUserId(item.getUserId());
//            questionDto.setName(item.getName());
            questionDto.setDescription(item.getName());
            questionDto.setIsUserTrue(1);
            questionService.addQuestion(questionDto);
            System.out.println("ok");

//        保存发送信息
//            Message message = new Message();
//            message.setContent(text);
//            message.setUserId(item.getUserId());
//            message.setCreateTime(DateUtils.getNowDate());
//            messageMapper.insertMessage(message);

        }


    }


    /**
     * 发送罚款消息
     *
     * @return 结果
     */
    @Transactional
    @Override
    public void sendFineMessage() {
        int penaltyDay = Integer.parseInt(sysDictDataMapper.selectValueByType("sys_penalty_day"));
        String penaltyRate =sysDictDataMapper.selectValueByType("sys_penalty_rate");
        int shouldPayDay = Integer.parseInt(sysDictDataMapper.selectValueByType("sys_pay_day"));

        // 将String转换为BigDecimal
        BigDecimal rate = new BigDecimal(penaltyRate);

        List<EmailDto> emaiLDtos = lendMessageMapper.selectExpireBookByDay(penaltyDay);
        //          设置时间格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (EmailDto item: emaiLDtos
        ) {

            //            生成罚款
            Penalty penalty = new Penalty();
            Book book  = bookMapper.selectBookByBookId(item.getBookId());
            penalty.setBookId(book.getBookId());
            penalty.setPenaltyPrice(book.getPrice().multiply(rate));
            penalty.setUserId(item.getUserId());
            penalty.setLendId(item.getLendId());
            penalty.setCreateTime(DateUtils.getNowDate());

            Date currentDate = new Date();//获取当前时间
            Calendar calendar = Calendar.getInstance();//计算应还日期，amount：通过字典管理，20就是20天后
            calendar.setTime(currentDate);
            calendar.add(Calendar.DATE, shouldPayDay);
            Date shouldTime = calendar.getTime();
            penalty.setShouldTime(shouldTime);

            penaltyMapper.insertPenalty(penalty);

//            shouldreturntime = shouldreturntime + Interval 30 Day
//            throw new RuntimeException("添加用户行为SQL执行异常");


            String shouldBackTime = sf.format(item.getShouldBackTime());
//          发送邮件
//            SimpleMailMessage mailMessage = new SimpleMailMessage();
            String text = "由于您借阅的《" + item.getName() + "》  借阅id = " + item.getLendId() + " 超过"+penaltyDay+"日未归还，已经生成罚款,罚款id=" + penalty.getPenaltyId()+"，请及时缴纳！";
//            设置发送人
//            mailMessage.setFrom("3407976203@qq.com");
//            邮件主题
//            mailMessage.setSubject("图书管理系统：罚款通知");
//            邮件内容
//            mailMessage.setText(text);
//            收件人
//            mailMessage.setTo(item.getEmail());
//            javaMailSender.send(mailMessage);

            //添加到个人消息中
            QuestionDto questionDto = new QuestionDto();
            questionDto.setContent(text);
            questionDto.setUserId(item.getUserId());
//            questionDto.setName(item.getName());
            questionDto.setDescription(item.getName());
            questionDto.setIsUserTrue(1);
            questionService.addQuestion(questionDto);

//            保存发送信息
//            Message message = new Message();
//            message.setContent(text);
//            message.setUserId(item.getUserId());
//            message.setCreateTime(DateUtils.getNowDate());
//            messageMapper.insertMessage(message);

//            更新借阅表state，表示提交丢失申请
            LendMessage lendMessage = new LendMessage();
            lendMessage.setLendId(item.getLendId());
            lendMessage.setState(1);
            lendMessageMapper.updateLendMessage(lendMessage);

        }
    }





}
